/*
 * tty.c
 *
 *  Created on: 2016-10-27
 *      Author: m
 */
#include "tty.h"
#include "keyboard.h"
#include "string.h"
#include "sub.h"
#include "global.h"


#define TTY_RING_Q_BUF_SIZE         (256)
static char tty_ring_q_buf[TTY_COUNT][TTY_RING_Q_BUF_SIZE] = {0};
void init_tty() {
    init_keyboard();
    for(int i = 0; i < TTY_COUNT; ++i) {
        TTY* tty = &g_tty_tab[i];
        int base;
        int limit;

        memset(tty, 0, sizeof(*tty));
        tty->console = &g_console_tab[i];
        q_init(&tty->q, tty_ring_q_buf[i], TTY_RING_Q_BUF_SIZE, 1);

        limit = V_MEM_SIZE / TTY_COUNT;
        limit = (limit / 160) * 160; //向下对齐到行
        base = (i * limit);
        init_console(tty->console, base, limit);
    }
    //console_clean_screen(&g_console_tab[0]); //using interrupt  DO NOT USE
    clear_screen2();
}


void tty_read(TTY* tty) {
    keyboard_read(&tty->q);
}

void tty_write(TTY* tty) {
    if(tty->q.count > 0) {
        u8 xkey;
        q_pop(&tty->q, &xkey);
        console_on_key_evnet(tty->console, xkey);
    }
}

void tty_task() {
    while(1) {
        TTY* cur_tty = &g_tty_tab[g_cur_tty_idx];
        tty_read(cur_tty);
        tty_write(cur_tty);
    }
}
